/****************************************************
          File Name:44-1.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Wed 10 Sep 2014 09:49:07 AM CST
*****************************************************/

#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<ctype.h>
#include<stdlib.h>
#define SIZE 100

void err(char *fun)
{
    perror(fun);
    exit(errno);
}

void trans(char string[SIZE])
{
    int i;
    for(i=0;string[i]!='\0';i++)
        string[i]=toupper(string[i]);
}
int main(int argc,char *argv[])
{
    int fd1[2], fd2[2];
    char buf[SIZE];

    if(pipe(fd1)==-1 || pipe(fd2)==-1)
        err("pipe");

    switch(fork())
    {
        case -1:
            err("fork");
        case 0:
            if(close(fd1[1])==-1)           // close stdio pipe write
                err("close fd1[1]");
            if(close(fd2[0])==-1)           // close return to parent read
                err("close fd2[0]");
            for(;;)
            {
                if(read(fd1[0],buf,SIZE)==-1)
                    err("read from parent fd1[0]");
                trans(buf);
                if(write(fd2[1],buf,SIZE)==-1)
                    err("write to parent Upper Case");
            }
        default:
            if(close(fd1[0])==-1)           // close stdio pipe read 
                err("close fd1[0]");
            if(close(fd2[1])==-1)           // close child write
                err("close fd2[1]");
            for(;;)
            {
                fgets(buf,SIZE,stdin);
                if(buf[0]=='\n')
                    exit(0);
                if(write(fd1[1],buf,SIZE)==-1)
                    err("get data from stdin");
                if(read(fd2[0],buf,SIZE)==-1)
                    err("read upper case from child");
                else
                    printf("%s",buf);
            }
    }

    exit(0);    // will never run
}
